package com.javaforever.clocksimplejee4.utils;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class AppTokenManager {
	private static Map<Long,String> loginUsers = new HashMap<Long,String>();
	private static Map<Long,Object> accessSets = new HashMap<Long,Object>();
	private static Map<Long,Timestamp> userClocks = new HashMap<Long,Timestamp>();
	private static int expriseMinutes = 15;
	
	public static String generateToken() {
		return UUID.randomUUID().toString();
	}
	
	public static Long getUserIdByToken(String token) {
		for (Long uid:loginUsers.keySet()) {
			if (loginUsers.get(uid).equals(token)) return uid;
		}
		return 0L;
	}
	
	public static String addUserId(Long userId,Set<String> accessSet) {
		if (loginUsers.containsKey(userId)) return loginUsers.get(userId);
		else {
			String token = AppTokenManager.generateToken();
			loginUsers.put(userId, token);
			accessSets.put(userId, accessSet);
			userClocks.put(userId, new Timestamp(System.currentTimeMillis()));
			return token;
		}		
	}
	
	public static void removeUserId(Long userId) {
		loginUsers.remove(userId);
		accessSets.remove(userId);
		userClocks.remove(userId);
	}
	
	public static void removeUserIdByToken(String token) {
		if (!isLoginUsingToken(token)) return;
		else {
			removeUserId(getUserIdByToken(token));
		}
	}
	
	public static boolean isLoginUsingUserId(Long userId) {
		if (loginUsers.containsKey(userId)) {
			Timestamp now = new Timestamp(System.currentTimeMillis());
			Timestamp lastCheckTime = userClocks.get(userId);
			if (now.getTime()-lastCheckTime.getTime() < expriseMinutes*60*1000) {
				userClocks.put(userId, now);
				return true;
			}else {
				removeUserId(userId);
				return false;
			}
		}
		else return false;
	}
	
	public static boolean isLoginUsingToken(String token) {
		if (loginUsers.containsValue(token)) {
			Long userId = getUserIdByToken(token);
			Timestamp now = new Timestamp(System.currentTimeMillis());
			Timestamp lastCheckTime = userClocks.get(userId);
			if (now.getTime()-lastCheckTime.getTime() < expriseMinutes*60*1000) {
				userClocks.put(userId, now);
				return true;
			}else {
				removeUserId(userId);
				return false;
			}
		}
		else return false;
	}

	public static boolean canAccess(String token, String accessUrl) {
		if (!isLoginUsingToken(token)) return false;
		Long userId = getUserIdByToken(token);
		if (userId == 0L) return false;
		Set<String> myaccess = (Set<String>)accessSets.get(userId);
		if (myaccess!=null&&myaccess.contains(accessUrl)) return true;
		else return false;
	}
}
